package servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Admin;
import bean.User;
import mapper.UserMapper;
import service.LoginService;
import service.UserInfoService;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LoginService service = new LoginService();
		String operation = request.getParameter("operation");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		switch(operation) {
		case "logout": 
			request.getSession().removeAttribute("user");
			response.sendRedirect(request.getContextPath() + "/login.html");
			break;
		case "adminlogout": 
			request.getSession().removeAttribute("admin");
			response.sendRedirect(request.getContextPath() + "/admin/login.html");
			break;
		case "login": 
			UserMapper userMapper = new UserInfoService().getMapper();
			String openid = request.getParameter("openid");
			if (openid == null || openid == "")
				response.sendRedirect(request.getContextPath() + "/login.html");
			User user = userMapper.findByOpenid(openid);
			if (user == null) {
				userMapper.addUserOnlyOpenid(openid);
				user = userMapper.findByOpenid(openid);
			}
			request.getSession().setAttribute("user", user);
			response.sendRedirect(request.getContextPath() + "/index.html");
//			String access_token = request.getParameter("access_token");
//			String url = "https://graph.qq.com/user/get_user_info?" + 
//					"access_token="+access_token+"&" + 
//					"oauth_consumer_key=101478977&" + 
//					"openid=" + openid;
//			String resultString = httpRequest(url);
//			String picurl = resultString.split(",")[4].split(":")[1].split("\"")[1];
			break;
		case "adminlogin": 
			Admin admin = service.loginCheck(username, password);
			if (admin == null) {
				request.getSession().invalidate();
				response.getWriter().write("{\"message\":\"用户名或密码错误！\"}");
			}else {
				request.getSession().setAttribute("admin", admin);
				response.getWriter().write("{\"message\":\"登录成功！\"}");
			}
			break;
		case "info" : break;
		}
	}
	 /** 
     * 发起http请求获取返回结果 
     * @param req_url 请求地址 
     * @return 
     */ 
    public static String httpRequest(String req_url) {
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(req_url);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  

            httpUrlConn.setDoOutput(false);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  

            httpUrlConn.setRequestMethod("GET");  
            httpUrlConn.connect();  

            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

        } catch (Exception e) {  
        	System.out.println(e.getMessage());
        }  
        return buffer.toString();  
    }
}
